package com.byd.dilink.service.provide;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
     * 此类描述的是：  http工具类
     * @author: chen.tengda@byd.com  
     * @version: 2018年9月12日 下午5:44:08
 */
public class HttpUtil {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

	private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(20000)
			.build();// 设置请求和传输超时时间

	/**
	 * 
	     * 此方法描述的是：  
		 * @Description: 
	     * @author: chen.tengda@byd.com  
	     * @createTime: 2019年11月14日 下午4:49:09
		 * @param strURL
		 * @param params
		 * @return   
		 * @return String
	 */
	public static String postJson(String strURL, String params) {
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(strURL);
			/*
			 * 打开于URL之间的连接
			 */
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setConnectTimeout(100000);
			connection.setReadTimeout(200000);
			// 设置请求方式
			connection.setRequestMethod("POST");
			// 设置接收数据的格式
			connection.setRequestProperty("Accept", "application/json");
			// 设置发送数据的格式
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();// 连接
			OutputStreamWriter out = new OutputStreamWriter(
					// 获得URL connection对象对应的输出流
					connection.getOutputStream(), "UTF-8");
			// 添加请求参数
			out.append(params);
			out.flush();
			out.close();
			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					// 定义BufferReader输入流来读取URL的相应
					connection.getInputStream()));
			String lines;
			StringBuilder sb = new StringBuilder(64);
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			return sb.toString();
		} catch (IOException e) {
			return "POST资源失败：" + e.getMessage();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	/**
	 * 
	     * 此方法描述的是：  
		 * @Description: 
	     * @author: chen.tengda@byd.com  
	     * @createTime: 2019年11月14日 下午4:49:03
		 * @param strURL
		 * @param params
		 * @return   
		 * @return String
	 */
	public static String postTsm(String ip, int port, String strURL, String params) {
		String responseStr = "{\"error\":\"error\"}";
		try {
			HttpPost httpPost = new HttpPost(strURL);
			httpPost.setHeader("Accept", "application/json"); // 设置接收数据的格式
			httpPost.setHeader("Content-Type", "application/json"); // 设置发送数据的格式
			httpPost.setConfig(requestConfig);
			StringEntity requestEntity = new StringEntity(params, "utf-8");
			httpPost.setEntity(requestEntity);
			CloseableHttpResponse response = null;
			try {
				HttpHost httpTarget = new HttpHost(ip, port);
				response = httpClient.execute(httpTarget, httpPost);
				HttpEntity responseEntity = response.getEntity();
				// 请求和响应状态
				Header[] statusHeader = response.getHeaders("status");
				Header[] optDescHeader = response.getHeaders("desc");
				if (responseEntity != null) {
					responseStr = EntityUtils.toString(responseEntity, "utf-8");
				}
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (Exception ex) {
			LOGGER.error("推送数据异常：Exception={}", ex.toString(), ex);
		}
		return responseStr;
	}

}
